package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService ;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        User user = userService.findByUsername(username); // 用户信息  用户角色信息  角色的权限信息
        if(user==null){
            return null;
        }

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        Set<Role> roles = user.getRoles();
        roles.forEach(role -> {
            // 框架在接收到认证信息的时候 如何区分是 角色 还是 权限呢 ?
            // 如果是以ROLE_开头的 , 就认为是角色 , 否则是权限

            //添加认证信息
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));

            //获取权限信息
            Set<Permission> permissions = role.getPermissions();
            permissions.forEach(permission -> authorities.add(new SimpleGrantedAuthority(permission.getKeyword())));
        });

        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }

    public static void main(String[] args) {
        // $2a$10$MVglONkFeP8ValRHcawcU.qk2M6SXrW8AVi32AzfsN79ou31gvB8q
        // $2a$10$ozoBjKCMF25tnRugMz0W.uuvj7LoUcehwvawD2EDdNhI1jo0NR71u
        //String encode = new BCryptPasswordEncoder().encode("123456");
        //System.out.println(encode);

        //String encode = "$2a$10$ozoBjKCMF25tnRugMz0W.uuvj7LoUcehwvawD2EDdNhI1jo0NR71u";
        //boolean matches = new BCryptPasswordEncoder().matches("1234568", encode);
        //System.out.println(matches);

        //$2a$10$MVglONkFeP8ValRHcawcU.qk2M6SXrW8AVi32AzfsN79ou31gvB8q
        // 加盐   123456 + 随机字符串(盐) = 密文

        // 密文 ---> 提取盐(随机字符串) + 明文 = 密文

    }

}
